package com.baidu.logindemos.db.model

import android.content.Context
import android.content.SharedPreferences
import com.baidu.logindemos.ui.main.IRepository
import com.baidu.logindemos.ui.main.IUserModel
import java.io.File

/**
 * SharedPreferences 工具类
 * saveUser
 * getUser
 */
class IUserModelImpl private constructor(val mIRepository: IRepository): IUserModel {
    private lateinit var sp: SharedPreferences


    companion object{
        val SP_NAME = "login_demo"
        val NAME_KEY = "name"
        val PASSWORD_KEY = "password"

        fun getInstance(repository: IRepository):IUserModel{
            return IUserModelImpl(repository)
        }
    }

    /**
     * 必须先调用init方法
     */
    fun init(context: Context) {
        sp = context.getSharedPreferences("login_demo", Context.MODE_PRIVATE)
    }

    /**
     * 保存用户信息
     */
    override fun saveUser(user: UserModel){
        sp.edit().also {
            it.putString(NAME_KEY, user.name)
            it.putString(PASSWORD_KEY, user.password)
            val result = it.commit()

        }
    }

    /**
     * 获取用户信息
     */
    override fun getUser(name:String):UserModel?{
        val nameValue = sp.getString(NAME_KEY, "")
        if (name == nameValue){
            val passwordValue = sp.getString(PASSWORD_KEY,"")!!
            return UserModel(nameValue, passwordValue)
        }else{
            return null
        }
    }

}